/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Ventas_Carrito.java
 *
 * Created on 28/02/2011, 08:40:14 AM
 */
package puntoventa;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.view.JasperViewer;

/**
 *
 * @author Gustavo Diaz
 */
public class Ventas_Carrito extends javax.swing.JFrame {

    private DefaultTableModel modelo;
    int suma = 0;

    /** Creates new form Ventas_Carrito */
    public Ventas_Carrito() {
        initComponents();
        this.setLocationRelativeTo(this);
        modelo = (DefaultTableModel) this.ventaTable.getModel();

        int delay = 1;   // delay for 5 sec.
        int period = 1;  // repeat every sec.


        // Get rotation the local date and time .
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(
                new TimerTask() {

                    public void run() {

                        Date.setText(Main.ObtenerHora());
                        // Set the variable in Date JLabel
                    }
                }, delay, period);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        CampoEfectivo = new javax.swing.JTextField();
        NuevaVB = new javax.swing.JButton();
        SalirB = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        AgregarPB = new javax.swing.JButton();
        CobrarB = new javax.swing.JButton();
        CancelarVB = new javax.swing.JButton();
        Efectivo = new javax.swing.JLabel();
        Total = new javax.swing.JLabel();
        Paga = new javax.swing.JLabel();
        Cambio = new javax.swing.JLabel();
        Date = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        ventaTable = new javax.swing.JTable();
        Label1 = new javax.swing.JLabel();
        Label2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Lucida Grande", 0, 14));
        jLabel2.setText("Total:");

        jLabel3.setFont(new java.awt.Font("Lucida Grande", 0, 14));
        jLabel3.setText("Paga:");

        NuevaVB.setText("Nueva Venta ");
        NuevaVB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                NuevaVBActionPerformed(evt);
            }
        });

        SalirB.setText("Salir de Ventas");
        SalirB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SalirBActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Lucida Grande", 0, 14));
        jLabel4.setText("Su cambio:");

        AgregarPB.setText("Agregar Producto");
        AgregarPB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AgregarPBActionPerformed(evt);
            }
        });

        CobrarB.setText("Cobrar ");
        CobrarB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CobrarBActionPerformed(evt);
            }
        });

        CancelarVB.setText("Cancelar Compra ");
        CancelarVB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CancelarVBActionPerformed(evt);
            }
        });

        Efectivo.setFont(new java.awt.Font("Lucida Grande", 0, 16));
        Efectivo.setText("Efectivo:");

        Total.setFont(new java.awt.Font("Lucida Grande", 0, 14));
        Total.setText("$0.00");

        Paga.setFont(new java.awt.Font("Lucida Grande", 0, 14));
        Paga.setText("$0.00");

        Cambio.setFont(new java.awt.Font("Lucida Grande", 0, 14));
        Cambio.setText("$0.00");

        Date.setText("YYYY/MM/DD HH:MM:SS");

        jLabel5.setFont(new java.awt.Font("Lucida Grande", 0, 24));
        jLabel5.setText("Venta de Articulos");

        ventaTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Cantidad", "Nombre", "Precio"
            }
        ));
        ventaTable.setEnabled(false);
        jScrollPane1.setViewportView(ventaTable);

        Label1.setFont(new java.awt.Font("Tahoma", 1, 48)); // NOI18N
        Label1.setText("1:");

        Label2.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        Label2.setText("3: Cobré");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 236, Short.MAX_VALUE)
                        .addComponent(Date))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(layout.createSequentialGroup()
                                    .addGap(9, 9, 9)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addGroup(layout.createSequentialGroup()
                                            .addComponent(Efectivo)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 22, Short.MAX_VALUE)
                                            .addComponent(CampoEfectivo, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addComponent(NuevaVB, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE)))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(Label1)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(AgregarPB, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                    .addComponent(CancelarVB, javax.swing.GroupLayout.Alignment.TRAILING)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(Label2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel4)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(SalirB, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE)
                                            .addComponent(CobrarB, javax.swing.GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE))
                                        .addGap(138, 138, 138)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(jLabel2)
                                            .addComponent(jLabel3))))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(Total)
                                    .addComponent(Paga)
                                    .addComponent(Cambio)))
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 371, Short.MAX_VALUE)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(Date, javax.swing.GroupLayout.DEFAULT_SIZE, 32, Short.MAX_VALUE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(Label1)
                            .addComponent(AgregarPB, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addComponent(CancelarVB, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(Total))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(Paga))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(Cambio)
                            .addComponent(Label2)))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(CobrarB, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(CampoEfectivo, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(Efectivo)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(NuevaVB, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(SalirB, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void NuevaVBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NuevaVBActionPerformed
        try {
            DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
            Connection conexion = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/PDV", "root", "");
            Statement s = (Statement) conexion.createStatement();
            s.executeUpdate("delete from compras");

            for (int x = 0; x < modelo.getRowCount(); x++) {
                modelo.removeRow(x);
            }

            if (modelo.getRowCount() == 1) {
                modelo.removeRow(0);
            }



            conexion.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Nueva Venta!");
        Total.setText("$0.00");
        Paga.setText("$0.00");
        Cambio.setText("$0.00");
    }//GEN-LAST:event_NuevaVBActionPerformed

    public void getID() {

        try {
            DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
            Connection conexion = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/PDV", "root", "");
            Statement s = (Statement) conexion.createStatement();
            ResultSet rs = s.executeQuery("select * from compras");
            Object[] fila = new Object[4];

            while (rs.next()) {
                String pre = rs.getString("Precio");
                fila[0] = rs.getString("ID");
                fila[1] = rs.getString("Cantidad");
                fila[2] = rs.getString("Nombre");
                fila[3] = pre;
                modelo.addRow(fila);
                this.ventaTable.setModel(modelo);
                suma = suma + Integer.parseInt(pre);

            }

//            ResultSet f=s.executeQuery("select id,sum(precio) from compras group by ");
//            f.next();
            Total.setText("$" + suma + ".00");
            //ventaTable.setModel(new javax.swing.table.DefaultTableModel(fila, renglones));
            conexion.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void AgregarPBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AgregarPBActionPerformed
        Carrito AgregaP = new Carrito();
        AgregaP.setVisible(true);
        this.dispose();
    }//GEN-LAST:event_AgregarPBActionPerformed

    private void CobrarBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CobrarBActionPerformed
        if (CampoEfectivo.getText().compareTo("") == 0) {
            JOptionPane.showMessageDialog(null, "No ha puesto el importe de pago.", "Atencion", JOptionPane.INFORMATION_MESSAGE);
        } else {
            int c = Integer.parseInt(CampoEfectivo.getText());
            int a = c - suma;
            Paga.setText("$" + c + ".00");
            Cambio.setText("$" + a + ".00");
            try {
                ImprFact();
            } catch (JRException ex) {
                Logger.getLogger(Ventas_Carrito.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                Logger.getLogger(Ventas_Carrito.class.getName()).log(Level.SEVERE, null, ex);
            }
        }



    }//GEN-LAST:event_CobrarBActionPerformed

    private void CancelarVBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelarVBActionPerformed
        try {
            DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
            Connection conexion = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/PDV", "root", "");
            Statement s = (Statement) conexion.createStatement();
            s.executeUpdate("delete from compras");

            for (int x = modelo.getRowCount() - 1; x > 0; x--) {
                System.out.println("contador =" + x + "");
                modelo.removeRow(x);
            }

            if (modelo.getRowCount() == 1) {
                modelo.removeRow(0);
            }



            conexion.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("1");
    }//GEN-LAST:event_CancelarVBActionPerformed

    private void SalirBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SalirBActionPerformed
        Inicio Ini = new Inicio();
        Ini.setVisible(true);
        this.dispose();
    }//GEN-LAST:event_SalirBActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed

    }//GEN-LAST:event_formWindowClosed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Ventas_Carrito().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton AgregarPB;
    private javax.swing.JLabel Cambio;
    private javax.swing.JTextField CampoEfectivo;
    private javax.swing.JButton CancelarVB;
    private javax.swing.JButton CobrarB;
    private javax.swing.JLabel Date;
    private javax.swing.JLabel Efectivo;
    private javax.swing.JLabel Label1;
    private javax.swing.JLabel Label2;
    private javax.swing.JButton NuevaVB;
    private javax.swing.JLabel Paga;
    private javax.swing.JButton SalirB;
    private javax.swing.JLabel Total;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable ventaTable;
    // End of variables declaration//GEN-END:variables

    private void ImprFact() throws JRException, SQLException {
        Map mapa = new HashMap();
        mapa.put("suma", 33);
        Connection c = DriverManager.getConnection("jdbc:mysql://localhost/pdv", "root", "");
        // TODO code application logic here
        JasperReport reporte = JasperCompileManager.compileReport("reporte/factura.jrxml");
        JasperPrint print = JasperFillManager.fillReport(reporte, mapa, c);
        JasperViewer visor = new JasperViewer(print);
        visor.setVisible(true);

    }
}
